#include "Udpcline.hpp"

#include "Cond.hpp"

#include "Lock.hpp"
#include "Log.hpp"

#include <iostream>
#include <string>
#include <stdlib.h>
#include <pthread.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

// 用户端不仅要向服务器发消息，还要接服务器发送的消息

int sockfd = -1;
struct sockaddr_in server;

void ClineQuit(int signo)
{
    (void)signo;
    const std::string quit="QUIT";
    int n=::sendto(sockfd,quit.c_str(),quit.size(),0,(sockaddr*)(&server),sizeof(server));
    exit(0);
}

void* Recver(void* args)
{
    while(true)
    {
        (void)args;
        struct sockaddr_in temp;
        socklen_t len=sizeof(temp);
        char buffer[1024];
        int n=::recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(sockaddr*)(&temp),&len);
        if(n>0)
        {
            buffer[n]=0;
            std::cout<<buffer<<std::endl;
            
        }
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << argv[0] << " 是不是忘记输入ip或者端口号了" << std::endl;
        exit(1);
    }

    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    // 创建socket
    sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);

    if (sockfd < 0)
    {
        std::cout << "创建套接字失败" << std::endl;
        exit(1);
    }

    // 填入相应的网络信息
    memset(&server,0,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = ::inet_addr(server_ip.c_str());
    server.sin_port = ::htons(server_port);

    // 发送相应的信息

    // 创建线程，线程执行相应的
    pthread_t td;

    // 该线程启动，接收来自服务器的消息
    pthread_create(&td, nullptr, Recver, nullptr);

    const std::string online = "......我来啦！";
    int n = ::sendto(sockfd, online.c_str(), online.size(), 0, (sockaddr *)(&server), sizeof(server));

    while (true)
    {
        std::cout << "Please Enter# ";
        std::string message;
        std::getline(std::cin, message);

        std::cout<<"message is  "<<message<<std::endl;

        int n = ::sendto(sockfd, message.c_str(), message.size(), 0, (sockaddr *)(&server), sizeof(server));
        (void)n;
    }
}